package com.yunshu.yunshuapp;

import android.app.ActivityManager;
import android.app.Notification;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.igexin.sdk.PushManager;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.xiaomi.mipush.sdk.MiPushClient;
import com.yunshu.yunshuapp.banner.BannerClass;
import com.yunshu.yunshuapp.kuaixun.KuaixunListActivity;
import com.yunshu.yunshuapp.network.YSCallback;
import com.yunshu.yunshuapp.network.YSRequest;
import com.yunshu.yunshuapp.tongxunlu.TongxunluActivity;
import com.yunshu.yunshuapp.user.LoginActivity;
import com.yunshu.yunshuapp.xianhuo.Xianhuo;
import com.yunshu.yunshuapp.xianhuo.XianhuoActivity;
import com.yunshu.yunshuapp.zixunlist.ZixunListActivity;
import com.yunshu.yunshuapp.zixunlist.ZixunListAdapter;
import com.yunshu.yunshuapp.kuaixun.KuaixunListAdapter;

import com.yunshu.yunshuapp.user.UserInfoActivity;
import com.yunshu.yunshuapp.user.YSUser;
import com.yunshu.yunshuapp.utils.*;
import com.yunshu.yunshuapp.banner.ScrollBanner;
import com.yunshu.yunshuapp.zixunlist.ZixunListModel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class MainActivity extends AppCompatActivity implements Toolbar.OnMenuItemClickListener,  OnTapListener {


    private ScrollBanner banner;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    private RecyclerView list;
    private HomeListAdapter listAdapter;
    private int pageIndex;
    private Boolean pageEnd;
    private SwipeRefreshLayout mRefreshLayout;
    private YSRequest request;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        YSUser.initUser(this);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.mipmap.userinfo);
        toolbar.setOnMenuItemClickListener(this);

        this.initList();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();

//        PushManager.startWork(getApplicationContext(),
//                PushConstants.LOGIN_TYPE_API_KEY,"Ci3Ab24a2LxSdxMXdYN4BLqV");
//
//        Resources resource = this.getResources();
//        String pkgName = this.getPackageName();
//        CustomPushNotificationBuilder cBuilder = new CustomPushNotificationBuilder(
//                resource.getIdentifier(
//                        "notification_custom_builder", "layout", pkgName),
//                resource.getIdentifier("notification_icon", "id", pkgName),
//                resource.getIdentifier("notification_title", "id", pkgName),
//                resource.getIdentifier("notification_text", "id", pkgName));
//        cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL);
//        cBuilder.setNotificationDefaults(Notification.DEFAULT_VIBRATE);
//        cBuilder.setStatusbarIcon(this.getApplicationInfo().icon);
//        cBuilder.setLayoutDrawable(resource.getIdentifier(
//                "notification_icon", "mipmap", pkgName));
//        cBuilder.setNotificationSound(Uri.withAppendedPath(
//                MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "6").toString());
//        // 推送高级设置，通知栏样式设置为下面的ID
//        PushManager.setNotificationBuilder(this, 1, cBuilder);

        //初始化push推送服务
        if( shouldInit() && YSUtils.SYS_MIUI.equals(YSUtils.getSystem()) ) {
            MiPushClient.registerPush(this, "2882303761517559136", "5821755973136");
        }else {
            // com.getui.demo.DemoPushService 为第三方自定义推送服务
            PushManager.getInstance().initialize(this.getApplicationContext(), com.yunshu.yunshuapp.push.GetuiPushService.class);
            // com.getui.demo.DemoIntentService 为第三方自定义的推送服务事件接收类
            PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), com.yunshu.yunshuapp.push.GetuiIntentService.class);
        }
        request = new YSRequest(this);
        this.request();
        this.checkVersion();

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                if (YSUser.isLogin()) {
                    intent.setClass(MainActivity.this, UserInfoActivity.class);
                }else{
                    intent.setClass(MainActivity.this, LoginActivity.class);
                }
                startActivityForResult(intent, 0);
            }
        });
        if (YSUser.isLogin()){
            YSUser.instance().update(null,this); // 更新通讯录权限
        }
    }

    private boolean shouldInit() {
        ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = getPackageName();
        int myPid = android.os.Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    public void onStart() {
        super.onStart();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.yunshu.yunshuapp/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.yunshu.yunshuapp/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);

        if (listAdapter.bannerHolder != null)
            listAdapter.bannerHolder.banner.stop();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.disconnect();
    }

    /**
     * 轮播广播模拟数据
     *
     * @return

    public static String[] getBannerAd() {


        return new String[]{
                "http://o2o-uploaded-images.b0.upaiyun.com/home_config/image/20161220/0d403d3328f36eec817877641c0ac630.jpg",
                "http://o2o-uploaded-images.b0.upaiyun.com/home_config/image/20161220/09f20f670f36d3a426204c532734499f.jpg"
                };
    }
     */

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RESULT_OK:
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main , menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_userinfo:
                Intent intent = new Intent();
                intent.setClass(this,UserInfoActivity.class);
                startActivityForResult(intent, 0);
                break;
            default:break;
        }
        return true;

    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_setting:
                Intent intent = new Intent();
                intent.setClass(this, SettingActivity.class);
                startActivityForResult(intent, 0);
                break;
            default:break;
        }
        return true;
    }


    @Override
    public void onSingleTap(View v, int position) {

    }


    private void request() {

        new YSRequest(this).GET(YSRequest.HOMEPAGE, null, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                if (isSuccess == YSRequest.REQUEST_OK){
                    JsonNode pics = result.get("pic");
                    updateBanner(pics);
                }
            }
        });

        refreshList();
    }

    private void refreshList() {
        pageEnd = false;
        String params = "advert=1&audit=1&page=1&type=0";
        if(YSUser.instance().getKuaixunChannels() != null && YSUser.instance().getKuaixunChannels().length() > 0 ){
            params += "&channelname=" + YSUser.instance().getKuaixunChannels();
        }
        request.GET(YSRequest.XIANHUO_LIST, params, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                endRefreshing();
                if (isSuccess != YSRequest.REQUEST_OK) return;
                if (result == null || !result.isArray()) return;
                Iterator<JsonNode> iterator = result.iterator();
                ArrayList<Xianhuo> temp = new ArrayList<Xianhuo>();
                ObjectMapper mapper = new ObjectMapper();
                while (iterator.hasNext()){
                    String jsonstr = iterator.next().toString();
                    try {
                        Xianhuo model = mapper.readValue(jsonstr, Xianhuo.class);
                        temp.add(model);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                listAdapter.setModels(temp);
                if (temp.size() < 8) pageEnd = true;
                pageIndex +=1;
                reloadData();
            }
        });

    }

    private void reloadData() {
        runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                listAdapter.notifyDataSetChanged();
            }
        });
    }

    private void endRefreshing() {
        runOnUiThread(new Runnable() {      // UI thread
            @Override
            public void run() {
                mRefreshLayout.setRefreshing(false);
            }
        });

    }

    private void loadMoreList() {
        if (!request.getIsCompleted() || pageEnd) return;
        String params = "advert=1&audit=1&type=0&page=" + pageIndex;
        request.GET(YSRequest.XIANHUO_LIST, params, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                endRefreshing();
                if (isSuccess != YSRequest.REQUEST_OK) return;
                if (result == null || !result.isArray()) return;
                Iterator<JsonNode> iterator = result.iterator();
                ArrayList<Xianhuo> temp = new ArrayList<Xianhuo>();
                ObjectMapper mapper = new ObjectMapper();
                while (iterator.hasNext()){
                    String jsonstr = iterator.next().toString();
                    try {
                        Xianhuo model = mapper.readValue(jsonstr, Xianhuo.class);
                        temp.add(model);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                listAdapter.addFooterItem(temp);
                pageIndex +=1;
                if (temp.size() < 8) pageEnd = true;
                reloadData();
            }
        });

    }

    private void updateBanner(JsonNode banners) {
        if (banners == null || ! banners.isArray()) return;
        Iterator<JsonNode> ite = banners.iterator();
        ObjectMapper mapper = new ObjectMapper();

        ArrayList<String> bannerImgs = new ArrayList();
        while (ite.hasNext()){
            JsonNode node = ite.next();
            try {
                BannerClass iBanner = mapper.readValue(node.toString(), BannerClass.class);
                bannerImgs.add(iBanner.getImgUrl());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        final String[] ads1 = bannerImgs.toArray(new String[]{});
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                listAdapter.ads = ads1;
                listAdapter.notifyDataSetChanged();
            }
        });
    }

    private void checkVersion() {
        YSRequest request = new YSRequest(this);
        request.GET(YSRequest.checkUpdate,"", new YSCallback() {

            @Override
            public void onResponse(int isSuccess, JsonNode result) {
                if (isSuccess != YSRequest.REQUEST_OK) return;
                ObjectMapper mapper = new ObjectMapper();
                String jsonstr = result.toString();
                int newVersion = Integer.parseInt(jsonstr);
                PackageInfo packageInfo = null;
                try {
                    packageInfo = getPackageManager()
                            .getPackageInfo(getPackageName(), 0);
                    //获取APP版本versionName
                    String versionName = packageInfo.versionName;
                    //获取APP版本versionCode
                    int versionCode = packageInfo.versionCode;
                    if (newVersion > versionCode){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                needShengji();
                            }
                        });
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void needShengji() {

        new AlertDialog.Builder(this).setTitle("提示")//设置对话框标题

                .setMessage("发现新版本，建议您立刻点击\"确定\"，进行升级")//设置显示的内容 ;
                .setPositiveButton("确定",new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                        gotoUpdate();
                    }
                }).setNegativeButton("取消",new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件

            }
        }).show();
    }

    private void gotoUpdate() {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse("http://a.app.qq.com/o/simple.jsp?pkgname=com.yunshu.yunshuapp");
        intent.setData(content_url);
        startActivity(intent);
    }


    private void initList(){
        mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                refreshList();
            }
        });

        list = (RecyclerView) findViewById(R.id.list_view);
        // use a linear layout manager
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        //设置RecycleView的显示方向：（默认为垂直） 水平
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        list.setLayoutManager(mLayoutManager);

//        list.setHasFixedSize(true);
        listAdapter = new HomeListAdapter(getBaseContext());
        listAdapter.activity = MainActivity.this;
        list.setAdapter(listAdapter);

        list.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem ;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                //判断RecyclerView的状态 是空闲时，同时，是最后一个可见的ITEM时才加载
                if(newState==RecyclerView.SCROLL_STATE_IDLE&&lastVisibleItem+1==listAdapter.getItemCount()){
                    loadMoreList();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //最后一个可见的ITEM
                lastVisibleItem=layoutManager.findLastVisibleItemPosition();
            }
        });
    }
}
